package com.smarthealthring.mm.ui.activity;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.smarthealthring.mm.R;
import com.smarthealthring.mm.base.BaseActivity;
import com.smarthealthring.mm.base.IPresenter;
import com.smarthealthring.mm.ble.BdProtocol;
import com.smarthealthring.mm.ble.RtEvent;
import com.smarthealthring.mm.clj.blesample.adapter.DeviceAdapter;
import com.smarthealthring.mm.clj.blesample.comm.ObserverManager;
import com.smarthealthring.mm.utils.ComToolBar;
import com.smarthealthring.mm.utils.RxBus;
import com.smarthealthring.mm.utils.RxBusBaseMessage;
import com.smarthealthring.mm.utils.SPUtils;
import com.smarthealthring.mm.widgets.WhewView;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleMtuChangedCallback;
import com.clj.fastble.callback.BleRssiCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.jakewharton.rxbinding2.view.RxView;

import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * 搜索蓝牙界面
 */
public class SearchBtActivity extends BaseActivity {
    private static final String TAG = SearchBtActivity.class.getSimpleName();

    @BindView(R.id.iv_search_bt)
    ImageView mIvSearching;
    @BindView(R.id.whewView)
    WhewView mWhewView;
    @BindView(R.id.tv_scan_status)
    TextView mTvStatus;

    private DeviceAdapter mDeviceAdapter;
    //显示搜索状态
    Button btn_scan;

    @Override
    protected void initComToolBar() {
        ImageView ivLeft = ComToolBar.setleftImg(mContext, R.drawable.back_white);
        RxView.clicks(ivLeft)
                .subscribe(o -> finish());
        ComToolBar.setTitle(mContext, "设备搜索中");
    }

    @Override
    protected int getLayout() {
        return R.layout.act_search_bt;
    }

    @Override
    protected void initEventAndData(@Nullable Bundle savedInstanceState) {
        //点击设备开始连接
        mDeviceAdapter = new DeviceAdapter(this);
        mDeviceAdapter.setOnDeviceClickListener(new DeviceAdapter.OnDeviceClickListener() {
            @Override
            public void onConnect(BleDevice bleDevice) {
                if (BleManager.getInstance().isBlueEnable()&&!BleManager.getInstance().isConnected(bleDevice)) {
                    BleManager.getInstance().cancelScan();
                    connect(bleDevice);
                }
            }

            @Override
            public void onDisConnect(BleDevice bleDevice) {
                if (BleManager.getInstance().isConnected(bleDevice)) {
                    // 解绑，改为解除绑定状态
                    // 解绑完成断开连接
                    BdProtocol.unBond(bleDevice);
                    SPUtils.setInt(SPUtils.BOND_STATE, 0);
                }
            }

            @Override
            public void onDetail(BleDevice bleDevice) {
                if (BleManager.getInstance().isConnected(bleDevice)) {
//                    Intent intent = new Intent(mContext, OperationActivity.class);
//                    intent.putExtra(OperationActivity.KEY_DATA, bleDevice);
//                    startActivity(intent);
                }
            }
        });
        ListView listView_device = (ListView) findViewById(R.id.list_device);
        btn_scan = (Button) findViewById(R.id.btn_scan);
        listView_device.setAdapter(mDeviceAdapter);

        startScan();
        registerEvent();
    }

    /**
     * 扫描出设备列表
     */
    private void startScan() {
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                mDeviceAdapter.clearScanDevice();
                mDeviceAdapter.notifyDataSetChanged();
                mWhewView.start();
                mTvStatus.setText(getString(R.string.stop_scan));
                Log.e("开始搜索设备===","in...");
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                // 必须包含FIT才会添加到列表
//                if (bleDevice.getName() != null && bleDevice.getName().contains("FIT")) {
//                    mDeviceAdapter.addDevice(bleDevice);
//                    mDeviceAdapter.notifyDataSetChanged();
//                }
                mDeviceAdapter.addDevice(bleDevice);
                mDeviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                mWhewView.stop();
                mTvStatus.setText(getString(R.string.start_scan));
            }
        });
    }

    private void connect(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                showLoading(true);
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                dismissLaoding();
                btn_scan.setText(getString(R.string.start_scan));
                Toast.makeText(mContext, getString(R.string.connect_fail), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                dismissLaoding();
                mDeviceAdapter.addDevice(bleDevice);
                mDeviceAdapter.notifyDataSetChanged();

                readRssi(bleDevice);
                setMtu(bleDevice, 23);

                //保存下设备信息
                SPUtils.setString(SPUtils.DEVICE_MAC, bleDevice.getMac());
                SPUtils.setString(SPUtils.DEVICE_NAME, bleDevice.getName());
                SPUtils.setInt(SPUtils.DEVICE_RSSI, bleDevice.getRssi());

                Log.e("onConnectSuccess===", bleDevice.getMac() + "---" + bleDevice.getName() + "---" + bleDevice.getRssi());

                // 目前连接成功直接绑定会失败，没找到正确的回调，先延迟500ms作处理
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 绑定同步数据
                BdProtocol.mBluetoothGatt = gatt;
                BdProtocol.mBleDevice = bleDevice;
                BdProtocol.channel = BdProtocol.TIME_CHANNEL;
                BluetoothGattService RxService = gatt.getService(BdProtocol.RX_SERVICE2_UUID);
                BluetoothGattCharacteristic characteristic_w = RxService.getCharacteristic(BdProtocol.RX_CHAR_W2_UUID);
                BdProtocol.notifyBle(bleDevice, characteristic_w);

            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                dismissLaoding();
                mDeviceAdapter.removeDevice(bleDevice);
                mDeviceAdapter.notifyDataSetChanged();
                Log.e("searchBt===","断开重连。。。");

                // crash
                if (isActiveDisConnected) {
//                    Toast.makeText(mContext, getString(R.string.active_disconnected), Toast.LENGTH_LONG).show();
                } else {
//                    Toast.makeText(mContext, getString(R.string.disconnected), Toast.LENGTH_LONG).show();
//                    ObserverManager.getInstance().notifyObserver(bleDevice);
                }

                // 5秒后重连
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (SPUtils.getInt(SPUtils.BOND_STATE, 0) == 1) {
                    BdProtocol.connectWithMac(SPUtils.getString(SPUtils.DEVICE_MAC, ""));
                }
            }
        });
    }

    private void readRssi(BleDevice bleDevice) {
        BleManager.getInstance().readRssi(bleDevice, new BleRssiCallback() {
            @Override
            public void onRssiFailure(BleException exception) {
                Log.i(TAG, "onRssiFailure" + exception.toString());
            }

            @Override
            public void onRssiSuccess(int rssi) {
                Log.i(TAG, "onRssiSuccess: " + rssi);
            }
        });
    }

    private void setMtu(BleDevice bleDevice, int mtu) {
        BleManager.getInstance().setMtu(bleDevice, mtu, new BleMtuChangedCallback() {
            @Override
            public void onSetMTUFailure(BleException exception) {
                Log.i(TAG, "onsetMTUFailure" + exception.toString());
            }

            @Override
            public void onMtuChanged(int mtu) {
                Log.i(TAG, "onMtuChanged: " + mtu);
            }
        });
    }

    @Override
    protected IPresenter createPresenter() {
        return null;
    }

    void registerEvent() {

        RxBus.getInstance().tObservable(RtEvent.BOND_SUCCESS_EVENT, RxBusBaseMessage.class)
                .subscribe(new Consumer<RxBusBaseMessage>() {
                    @Override
                    public void accept(RxBusBaseMessage rxBusBaseMessage) throws Exception {
                        Log.e("reg_bond_succ===","in...");
                        startActivity(new Intent(SearchBtActivity.this, HomeActivity.class));
                    }
                });
    }
}
